<template>
    <div class="userConfig " >
        <div class="controlBar mt-5">
            <button type="button" 
            @click="feetBack"
            class="btn btn-secondary">&lt;返回</button>    
        </div> 
        <div class="configItem mt-3 p-2 shadow  bg-white rounded">
            <h2 class="mt-2 ml-2">
                我的头像 
                <span class="badge badge-secondary">头像编辑</span>
            </h2>
            <div class="my-avatar mt-5">
                <div class="avatar-editor">
                    <div class="avatar-Item">
                        <h6 class="text-center">自定义图像</h6>
                        <avatar 
                        :width="100"
                        :height="100"
                        :border="10"
                        :scale="parseFloat(adjustment.zoom)"
                        :rotation="parseFloat(adjustment.rotate)"
                        :placeholderSvg="plhsvg"
                        @select-file="choseFile"
                        @dragimg="clickCustomImg"
                        ref="vueavatar"
                        />
                    </div>
                    <div class="avatar-Item" >
                        <div class="avatar-Item-spacerBorder text-black-50"
                            style="position: relative; bottom: -10px;"
                        ></div>
                    </div>
                    <div class="avatar-Item" >
                        <h6 class="text-center">我的头像</h6>
                        <div class="avatar-getter">
                            <img ref="myavatar"  alt="">
                        </div>
                       
                    </div>
                </div>
                <div  class="avatar-opr mt-5" >
                    <h5>图片调整：</h5>
                    <div class="opr-item">
                        <div class="form-group">
                            <label for="formControlRange">缩放：{{`( ${adjustment.zoom}x )`}}</label> &nbsp;
                            <span><input class="btn btn-secondary btn-sm"
                            @click="resetImageSetting(0)"
                             type="reset" value="重置"></span>
                            <input type="range"
                             :min="1"
                             :max="3"
                             :step="0.02"
                             v-model="adjustment.zoom"
                             @click="changeScale"
                             class="form-control-range" id="zoomRange">
                        </div>
                    </div>
                    <div class="opr-item">
                        <div class="form-group">
                            <label for="formControlRange">旋转：{{`(${adjustment.rotate})`}}&deg;</label> &nbsp;
                            <span><input class="btn btn-secondary btn-sm" 
                            @click="resetImageSetting(1)"
                            type="reset" value="重置"></span>
                            <input type="range" 
                            :min="-180"
                            :max="180"
                            :defaultValue="0"
                            :step="1"
                            @click="changeRotate"
                            v-model="adjustment.rotate"
                            class="custom-range" id="rotateRange">
                        </div>
                    </div>
                    <div class="opr-item d-flex justify-content-center
                        ">
                        <transition
                        name="imgBtn"
                       
                        :duration="{ enter: 1000, leave: 1000 }"
                        enter-active-class="animate__animated animate__fadeInRightBig"
                        leave-active-class="animate__animated animate__fadeOutLeftBig "
                        >
                            <button v-if="!adjustment.checkout" 
                            @click="getImage"
                            type="button" class="btn btn-primary">确定</button>
                            
                        </transition>
                         <transition
                        name="imgBtn2"
                        
                        :duration="{ enter: 1000, leave: 1000 }"
                        enter-active-class="animate__animated animate__fadeInDown "
                        leave-active-class="animate__animated animate__fadeOutDown"
                        >
                            <button v-if="adjustment.checkout" 
                            @click="openDialogue({
                                content:'提交新的头像',
                                fnArr:[
                                {
                                    title: '确定',
                                    fn: saveToServer
                                },
                                {
                                    title: '取消',
                                    fn: closeDialogue
                                }
                                ]
                            })"
                            type="button" class="btn btn-danger">保存</button>
                            
                        </transition>
                            
                    </div>
                </div>
            </div>
            
        </div>
        <div class="configItem mt-3 p-2 shadow  bg-white rounded">
            <h2 class="mt-2 ml-2">
                用户名 
                <span class="badge badge-secondary">昵称编辑</span>
            </h2>  
            <div class="nickEdit mt-5 mb-5 d-flex flex-column align-items-center">
                <!-- 操作区域 -->
                <div class="change-nickName d-flex justify-content-center">
                    <!-- 输入标签 -->
                    <div style="width: 70%;" class="col-auto">
                    <label class="sr-only" for="inlineFormInputGroup">Username</label>
                    <div class="input-group mb-2">
                        <div class="input-group-prepend">
                        <div class="input-group-text">新昵称</div>
                        </div>
                        <input type="text" 
                        name="用户昵称"
                        data-vv-scope="昵称"
                        v-validate="{
                            required : true,
                            'illegalchar' : true,
                            max: 20
                        }"
                        :maxlength="21"
                        v-model="nickName"
                        class="form-control " 
                        :class="{ 'is-invalid' : errors.first('用户昵称','昵称') }"
                        id="inlineFormInputGroup" placeholder="昵称修改">
                        <!-- 校验结果 -->
                        <div class="invalid-feedback">
                            {{  errors.first('用户昵称','昵称')  }}
                        </div>
                    </div>
                    </div>
                    <!-- 提交保存昵称 -->
                    <div style="width: 30%;" class="col-auto">
                    <button type="submit" 
                    @click="openDialogue({
                        content:'确定修改昵称',
                        fnArr:[
                        {
                            title: '确定',
                            fn: defenceForNickName
                        },
                        {
                            title: '取消',
                            fn: closeDialogue
                        }
                        ]
                    })"
                    class="btn btn-primary mb-2">保存</button>
                    </div>
                </div>
                
            </div>
        </div>
        <div class="configItem mt-3 p-2 shadow  bg-white rounded">
            <h2 class="mt-2 ml-2">
                修改密码 
                <span class="badge badge-secondary">设置新密码</span>
            </h2> 
            <div class="newPassphrass mt-5 mb-5">
                <div class="mb-3">
                    <div class="input-group is-invalid">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="validatedInputGroupPrepend">当前密码</span>
                    </div>
                    <input type="password"
                    data-vv-scope="密码"
                    name="当前密码"
                    v-validate="{
                        required : true,
                        'empInStr' : true,
                        max: 32
                    }"
                    :maxlength="33"
                    v-model="pass.origin"
                    :class="{ 'is-invalid' : errors.first('当前密码','密码') }"
                    class="form-control " aria-describedby="validatedInputGroupPrepend" >
                    </div>
                    <div class="invalid-feedback">
                    {{errors.first('当前密码','密码')}}
                    </div>
                </div>    

                <div class="mb-3">
                    <div class="input-group is-invalid">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="validatedInputGroupPrepend">新的密码</span>
                    </div>
                    <input type="password" 
                    name="新用密码"
                    ref="新的密码"
                    data-vv-scope="密码"
                    v-validate="{
                        required : true,
                        'empInStr' : true,
                        max: 32
                    }"
                    :maxlength="33"
                    v-model="pass.newpwd"
                    :class="{ 'is-invalid' : errors.first('新用密码','密码') }"
                    class="form-control " aria-describedby="validatedInputGroupPrepend" >
                    </div>
                    <div class="invalid-feedback">
                    {{errors.first('新用密码','密码')}}
                    </div>
                </div>    

                <div class="mb-3">
                    <div class="input-group is-invalid">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="validatedInputGroupPrepend">确认密码</span>
                        </div>
                        <input type="password" 
                        name="确认密码"
                        data-vv-scope="密码"
                        v-validate="{
                            required : true,
                            'empInStr' : true,
                            confirmed: '新的密码',
                            max: 32
                        }"
                        :maxlength="33"
                        v-model="pass.cmfpwd"
                        :class="{ 'is-invalid' : errors.first('确认密码','密码') }"
                        class="form-control " aria-describedby="validatedInputGroupPrepend" >
                    </div>
                    <div class="invalid-feedback">
                    {{ errors.first('确认密码','密码') }}
                    </div>
                </div>  

                <div class="mb-3 d-flex justify-content-center">
                    <button type="button" 
                    @click="openDialogue({
                        content:'确定修改密码',
                        fnArr:[
                        {
                            title: '确定',
                            fn: defenceChangePassphrass
                        },
                        {
                            title: '取消',
                            fn: closeDialogue
                        }
                        ]
                    })"
                    class="btn btn-primary">保存</button>
                </div>  
            </div>  
        </div>
        <!-- 消息提示 -->
        <transition
        
        :duration="{ enter: 1000, leave: 1000 }"
        enter-active-class="animate__animated animate__jackInTheBox"
        leave-active-class="animate__animated animate__fadeOut">
            <msg-toast
            v-if="msg.show"
            :from="msg.from"
            :content="msg.content"
            :opr="msg.opr"
            :loading="msg.loading"
            ></msg-toast>
        </transition>
    </div>
</template>

<script>
import avatar from "./components/VueAvatar.vue";
import { setUserAvatar , setUserNickName , changeUserPwd } from "../../../api/interface/users.js";
import { freshToken } from "../../../api/interface/token.js"; //重新请求token
import { tools } from "../../../api/tools.js";
import { getPublickey } from "../../../api/homePage.js";
import cryptico from "cryptico-js";
import msgToast from '../informationToast/infoToast.vue'; 

export default {
    components:{
        avatar,
        msgToast
    },
    data(){
        return {
            plhsvg: '<svg t="1609227262812" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2560" width="50" height="50"><path d="M896 192 128 192 128 832 896 832 896 192ZM1024 64 1024 64 1024 960 0 960 0 64 1024 64ZM832 768 192 768 192 640 384 320 647.008 640 832 512 832 576ZM640 352A3 3 2520 1 0 832 352 3 3 2520 1 0 640 352z" p-id="2561"></path></svg>', //默认上传提示图标
            adjustment:{
                zoom: 1,
                rotate: 0,
                filelist: 0,
                checkout: false
            },
            nickName: "",
            pass:{
                origin:"",
                newpwd:"",
                cmfpwd:""
            },
            msg:{
                content:"",
                show: false,
                opr:[],
                from:"",
                loading: false
            }
            
        }
    },
    watch:{
        
    },
    mounted() {
        
    },
    activated() {
        
        this.resetPwdContent();
        this.resetNickNameInput();
        this.checkUserAvatarLocalstorage();
        this.$validator.reset();

    },
    methods: {
        //重置图片编辑参数
        resetImageSetting( type ){
            // type : 0 代表缩放
            // type : 1 代表角度
            this.adjustment.checkout = false;
            switch( type ){
                case 0: 
                    this.adjustment.zoom = 1;
                break;
                case 1: 
                    this.adjustment.rotate = 0;
                break;
                default: return ;
            }
        },
        feetBack(){
            this.$router.back();            
        },
        //文件选择
        choseFile( file ){
            this.adjustment.filelist = file.length;
            // if(this.adjustment.filelist == 0){
            //     this.resetCustomPic();
            //     return ;
            // }
            
            this.adjustment.checkout = false;
        },
        //获取图片
        getImage(){
            this.adjustment.checkout = true;
            var img = this.$refs.vueavatar.getImageScaled();
            
            this.$refs.myavatar.src = img.toDataURL();
        },
        //恢复默认自定义图像
        resetCustomPic(){
            this.$refs.vueavatar.resetImage();

        },
        //调整图片大小
        changeScale(){
            this.adjustment.checkout = false;
        },
        //调整图片角度
        changeRotate(){
            this.adjustment.checkout = false;
        },
        //点击自定义图片
        clickCustomImg(){
            this.adjustment.checkout = false;
        },
        //图片保存，上传服务器
        saveToServer(){
            let that = this;
            this.controlLoading();
            var img = this.$refs.vueavatar.getImageScaled();
            const imgRes =  img.toDataURL();

            setUserAvatar({
                avatar : imgRes
            }).then(res=>{
                this.controlLoading();
                this.setAjaxReturnMsg( res.data.msg );
                
            }).catch(err=>{
                this.$httpError.checkResStatus(err.data,function(){
                    //重新请求生成token
                    freshToken().then(res=>{
                        localStorage.setItem("token", res.data.data.token);
                        that.saveToServer( );
                    })
                },that)
            });
            
        },
        //检查是否缓存自定义用户头像
        checkUserAvatarLocalstorage(){
            // myavatar
            if( !window ) return ;
            let avatar = window.localStorage.getItem('my_avatar');
            if( !avatar ) return ;
            this.$refs.myavatar.src = avatar;
        },
        //校验昵称的输入值
        validateNickName(){
            const field = this.$validator.fields.find({ name: '用户昵称' , scope: '昵称' });
            field.validator.validate('昵称.用户昵称').then(res=>{
                if( !res ){
                    
                }else{
                    this.saveNickName();   // 验证通过后请求接口的方法
                }
            }).catch();
            
            // this.$validator.validate().then(result => {
            //     if (!result) {
            //         console.log("sth wrong： ");
            //     } else {
            //         this.saveNickName();   // 验证通过后请求接口的方法
            //     }
            // });
        },
        //昵称保存
        saveNickName(){
            let that = this;
            this.controlLoading();
            setUserNickName({
                nickName: this.nickName
            }).then( res=>{
                //成功了 修改对话框
                this.controlLoading();
                this.setAjaxReturnMsg( res.data.msg );
            } ).catch(err=>{
                this.$httpError.checkResStatus(err.data,function(){
                    //重新请求生成token
                    freshToken().then(res=>{
                        localStorage.setItem("token", res.data.data.token);
                        that.saveNickName( );
                    })
                },that);
            });
            
        },
        //防抖控制昵称保存
        defenceForNickName: tools.debounceWithTrigger( function(){
            this.validateNickName();
        } , 1000 , true),
        //校验密码修改
        validatePassphrass(){
            const field = this.$validator.fields.find({ scope: '密码' });
            field.validator.validate("密码.*").then(res=>{
                if( !res ){

                }else{
                    this.changePassphrass();   // 验证通过后请求接口的方法
                }
            }).catch();
            // this.$validator.validate().then(result => {
            //     if (!result) {
            //         console.log("sth wrong");
            //     } else {
            //         this.changePassphrass();   // 验证通过后请求接口的方法
            //     }
            // });
        },
        //加密过程
        async encryptPassword(val){
            if( !this.$store.getters.getPublicKey ){
                let pub = await getPublickey();
                if(pub.code == 0 ){
                    this.$store.commit("setPublicKey", pub.data.key);  
                    
                }
                //异常处理 （未完成）
            }
            
            let enkey = cryptico.encrypt(val , this.$store.getters.getPublicKey)
            return enkey; 

        },
        //提交修改密码
        async changePassphrass(){
            let that = this;
            this.controlLoading();
            let pwdContent = {
                'cur_pwd': ( await this.encryptPassword(this.pass.origin) ).cipher, 
                'new_pwd': ( await this.encryptPassword(this.pass.newpwd) ).cipher,
                'cfm_pwd': ( await this.encryptPassword(this.pass.cmfpwd) ).cipher
            }
            changeUserPwd( pwdContent ).then( res=>{
                this.controlLoading();
                this.setAjaxReturnMsg( res.data.msg );
            } ).catch(err=>{
                this.$httpError.checkResStatus(err.data,function(){
                    //重新请求生成token
                    freshToken().then(res=>{
                        localStorage.setItem("token", res.data.data.token);
                        that.changePassphrass( );
                    })
                },that);
            });
            this.resetPwdContent();
        },
        //防抖限制提交
        defenceChangePassphrass: tools.debounceWithTrigger( function(){
            this.validatePassphrass();
        } , 1000 , true),
        //打开消息对话
        openDialogue({ content , fnArr }){
            this.msg.from = this;
            let btn = [];
            btn = btn.concat(fnArr);
            this.msg.opr = btn;
            this.msg.content = content;

            this.msg.show = true;
        },
        //控制加载标识
        controlLoading( ){
            this.msg.loading = !this.msg.loading;
        },
        //控制回现信息
        setAjaxReturnMsg( content ){
            let that = this;
            this.resetMsgDialogue();
            this.msg.content = content;
            this.msg.opr.length = 0;
            this.msg.opr.push({
                title: "返回",
                fn: that.closeDialogue
            });
        },
        //重置消息
        resetMsgDialogue(){
            this.msg.opr = [];
            this.msg.content = "";
            this.msg.loading = false;
        },
        //关闭对话
        closeDialogue(){
            this.resetMsgDialogue();
            this.msg.show = false;
        },
        resetPwdContent(){
            this.pass = {
                origin:"",
                newpwd:"",
                cmfpwd:""
            };
        },
        resetNickNameInput(){
            this.nickName = "";
        }
    }
}
</script>

<style lang="scss">
.userConfig{
    // height: 100%;
   .controlBar{
       width: 80%;
       margin: 0 auto;
   }
   .configItem{
       width: 80%;
       margin: 0 auto;
   }
}

.configItem{
    .my-avatar{
        display: flex;
        flex-direction: column;
        align-items: center;
        .avatar-editor{
            display: flex;
            justify-content: center;
            width: 100%;
            .avatar-Item{
                align-self: center;
            }
        }
        .avatar-opr{

        }
    }
    
}
.avatar-Item{
    .avatar-getter{
        display: inline-block;
        width: 120px;
        height: 120px;
        border: 1px solid grey;
        img{
            display: inline-block;
            width: 100%;
            height: 100%;
        }
    }
}

.avatar-Item-spacerBorder{
   height: 120px;
   border-left: 1px solid;
   margin: 0 3em;
   
}

.nickEdit{
    .change-nickName{
        width: 60%;
        margin: 0 auto;
    }
}

.newPassphrass{
    width: 60%;
    margin: 0 auto;
}

</style>